package undestiny.cookiedemo;

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class CookieController {

    @GetMapping("/setCookies")
    public String setCookies(HttpServletResponse response){
            //HttpServletRequest 装请求信息的类
            //HttpServletResponse 装返回信息的类
            Cookie cookie=new Cookie("sessionId","CookieTestInfo");
            response.addCookie(cookie);
            return "get cookies successfully";
    }



    //非注解方式获取cookie中对应的key值
    @GetMapping("/getCookies")
    public  String getCookies(HttpServletRequest request){
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("sessionId")){
                    return cookie.getValue();
                }
            }
        }
        return  null;
    }

    //注解方式获取cookie中对应的key值
    @GetMapping("/getCookies/annotation")
    public String testCookieValue(@CookieValue("sessionId") String sessionId ) {
        //前提是已经创建了或者已经存在cookie了，那么下面这个就直接把对应的key值拿出来了。
        System.out.println("testCookieValue,sessionId="+sessionId);
        return "SUCCESS";
    }

}
